<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Widget;
use Illuminate\Support\Facades\Log;

class GetData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
    *获取接口的数据
     */
    public function handle()
    {
        //获取接口数据
        $url  = 'https://news.baidu.com/widget?id=LocalNews&ajax=json&t='. time() * 1000;
        $row  = curl($url);

        if(empty($row['data']['LocalNews']['data']))
        {
            Log::info('接口数据获取失败！');
        }else{
            $data = $row['data']['LocalNews']['data'];

            if(!Widget::where('cityid', $data['cityid'])->count())
            {
                //把数据入库
                $widget = new Widget;

                $widget->pic        = json_encode($data['rows']['pic']) ?? '';
                $widget->first      = json_encode($data['rows']['first']) ?? '';
                $widget->second     = json_encode($data['rows']['second']) ?? '';
                $widget->cityid     = $data['cityid'] ?? 0;
                $widget->total      = $data['total'] ?? 0;
                $widget->result_num = $data['result_num'] ?? 0;
                $widget->name       = $data['name'] ?? '';
                $widget->province   = $data['province'] ?? 0;

                $widget->save();

            }
        }

    }
}
